<template>
  <div class="pz-list">
    <el-dialog 
      v-el-drag-dialog="{drag: true, full: true, resize: true}"
      title="业务平账" 
      :close-on-click-modal="false"
      :visible.sync="md.state"
      @close="closeMd"
      v-if="md.state"
    >
        <el-table
          :data="tableData"
          border
          height="250"
          :summary-method="getSummaries"
          show-summary
          style="width: 100%; margin-top: 20px">

          <!-- <el-table-column
            prop="cusName"
            label="客户"
            width="100">
          </el-table-column> -->
          <el-table-column
            prop="courseName"
            label="科目"
            width="180">
          </el-table-column>
          <el-table-column
            prop="money"
            label="订单金额"
            width="120">
          </el-table-column>
          <!-- <el-table-column v-if="incomeMoney"
            prop="incomeMoney"
            label="借"
            width="120">
          </el-table-column>
          <el-table-column
            prop="payMoney"
            label="贷"
            width="120">
          </el-table-column> -->
          <el-table-column property="incomeMoney" label="借" width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.incomeMoney" 
                        controls-position="right" 
                        style="width: 100px" 
                        class="inputClass" 
                        v-bind:disabled="scope.row.markOrder == '收'"
                        @change="editCollMo(scope.row)"></el-input>
            </template>
          </el-table-column>
          <el-table-column property="payMoney" label="贷" width="120" >
            <template slot-scope="scope">
              <el-input v-model="scope.row.payMoney" 
                        controls-position="right" 
                        style="width: 100px" 
                        class="inputClass" 
                        v-bind:disabled="scope.row.markOrder == '付'"
                        @change="editPayMo(scope.row)"></el-input>
            </template>
          </el-table-column>
          <el-table-column property="gainTime" label="日期(必填)">
            <template slot-scope="scope">
                <el-date-picker
                  v-model="scope.row.gainTime"
                  type="date"
                  controls-position="right" 
                  style="width: 100%" 
                  class="inputClass"
                  placeholder="选择日期"
                  value-format="yyyy-MM-dd">
              </el-date-picker>

            </template>
          </el-table-column>
          <el-table-column property="remark" label="摘要(必填)">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" controls-position="right" style="width: 100%" class="inputClass" ></el-input>
              
            </template>
          </el-table-column>
        </el-table>

        <!-- <el-form-item>
          <el-button type="primary" @click="onSubmit" :disabled="fm.sb.load">{{fm.sb.text}}</el-button>
        </el-form-item> -->
          <el-button class="btn" type="primary" @click="onSubmit" :disabled="fm.sb.load">{{fm.sb.text}}</el-button>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import elDragDialog from '@/directive/el-drag-dialog';
import UploadImg from '@/components/UploadImg';
import { getCourseId, serviceOffSet, payDebtList } from '@/api/services/order.service';

export default {
  name: 'PaylistPz',
  directives: { elDragDialog },
  props: [ 'state', 'data'  ],
  components: { UploadImg },
  computed: {
    ...mapGetters([ 'lunitNum', 'uname' ])
  },
  data() {
    return {
      md: { state: this.state },
      fm: {
        fname: 'addCusFm',
        sb: { load: false, text: '立即添加' },
        
        xs: {isShow: false},
      },
      tableData: [] //定义对冲列表数据
    }
    
  },
  created() {
    const that = this;
    


    let list = that.data;
    for(let i = 0; i<list.length; i++){
        if(Number(list[i].receivableBalance) < 0){
            getCourseId({courseNames: '应收账款'}).then(res=> {
            if(res.data == ""){
                $.misMsg("预收账款科目不存在请先添加");
            }else{
              // 贷方
              let receivableBalance = -(list[i].receivableBalance)
              let info = {
                fcId: res.data[0].id,
                orderId: list[i].id,
                incomeMoney:0,
                payMoney:receivableBalance,
                remark: "",
                gainTime: "",
                courseName:'应收账款',
                markOrder:"收",
                money: list[i].receivableBalance
              }
              that.tableData.push(info);
            }
        });
        }else{
            getCourseId({courseNames: '应付外调车费'}).then(res=> {
            if(res.data == ""){
                $.misMsg("应付外调车费科目不存在请先添加");
            }else{
              // 借方
              let info = {
                incomeMoney:list[i].receivableBalance,
                payMoney:0,
                orderId:list[i].id,
                remark:"",
                courseName:'应付外调车费',
                fcId:res.data[0].id,
                gainTime:"",
                money: list[i].receivableBalance,
                markOrder:"付"
              }
              that.tableData.push(info);
            }
        });
        }
    }



  },
  methods:{
    /* 合计 */
    getSummaries(param) {
        const { columns, data } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '总价';
            return;
          }
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] += ' 元';
          } else {
            sums[index] = ' ';
          }
        });

        return sums;
      },




    /* 关闭弹框 */
    closeMd(){
      this.$emit('getMdState', false);
    },
    /**
     * 提交表单
     */
    onSubmit(){
      const that = this;
      
      let gathInfo = [];
      let payInfoList = [];
      for(let i in that.tableData){
        if(that.tableData[i].markOrder == "收"){
          let morePayInfo = {
            fcId:that.tableData[i].fcId,
            orderId:that.tableData[i].orderId,
            morePayMoney:that.tableData[i].payMoney,
            remark:that.tableData[i].remark,
            gainTime:that.tableData[i].gainTime
          };
          gathInfo.push(morePayInfo);
        }else{
          let payInfo = {
            fcId:that.tableData[i].fcId,
            orderId:that.tableData[i].orderId,
            payMoney:that.tableData[i].incomeMoney,
            remark:that.tableData[i].remark,
            gainTime:that.tableData[i].gainTime
          };
          payInfoList.push(payInfo);
        }
      };

      that.fm.sb.load = true; 
      let loading = that.U.qloading('提交中，请稍后...');

      payDebtList({morePayInfo:gathInfo,payInfo:payInfoList}).then(res=> {
        
        that.fm.sb.load = false;
        that.U.qclose(loading);
        if(!res || res.code != 1){
          that.U.qerror(res.msg);
        }else{
          that.U.qsuccess(res.msg);
          // 关闭弹框
          that.closeMd();
          // 调用父组件方法-重新加载数据
          that.$emit('reloadDg');
        }
        
      });


      



      // that.$refs[that.fm.fname].validate((valid) => {
      //   if (!valid) {
      //     that.U.qerror('验证不通过');
      //     return false; 
      //   }else{
      //     that.fm.sb.load = true;                             // 添加按钮禁用效果
      //     let loading = this.U.qloading('提交中，请稍后...');   // 添加遮罩
          
      //     // 添加固定参数
          
      //     that.fm.ps.unitNum = this.lunitNum;
      //     that.fm.ps.cusType = (that.fm.ps.cusType).toString();
      //     // 新增推荐人
      //     that.fm.ps.recomMan =  that.fm.ps.serviceMan;
      //     adupCompanyCus(that.fm.ps,'save').then(res => {
      //       that.fm.sb.load = false;        // 取消按钮禁用效果
      //       that.U.qclose(loading);         // 关闭遮罩

      //       if(!res || res.code != 1){
      //         that.U.qerror(res.msg);
      //       }else {
      //         that.U.qsuccess(res.msg);

      //         // 关闭弹框
      //         that.closeMd();

      //         // 调用父组件方法-重新加载数据
      //         that.$emit('reloadDg');
      //       }

      //     });
      //   }
      // });
    },

    // 修改贷方
    editPayMo(row){
      const that = this;
      
      if(Number(row.payMoney) > -(Number(row.money)) || Number(row.payMoney) <= Number(0)){
        row.payMoney = row.money;
        that.U.qerror('修改的金额不能大于订单金额');
      }
    },

    // 修改借方
    editCollMo(row){
      const that = this;
      
      if(Number(row.incomeMoney) > Number(row.money) || Number(row.incomeMoney) <= Number(0)){
        row.incomeMoney = row.money;
        that.U.qerror('修改的金额不能大于订单金额');
      }
    },
  },
 }
</script>
<style lang="less" scoped>
.pz-list{
  .btn{
    margin-top: 100px;
    margin-bottom: 10px;
    margin-left: 40px;
  }
  .el-table{
      overflow:visible !important;
  }
        // .el-card__body {
        //     padding: 20px 20px 50px 20px;
        // }
        // .el-table__footer-wrapper{
        //     margin-top: -47px !important;
        // }
}
</style>